package cn.jiyun.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.junit.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Fay
 * @date 2022/6/29&19:05
 */

/**
 * 添加
 */
public class mongodbDemo3 {
    @Test
    public void add(){
        //建立连接
        MongoClient client = new MongoClient("127.0.0.1");
        //获取数据库
        MongoDatabase spitdb = client.getDatabase("spitdb");
        //获取集合
        MongoCollection<Document> spit = spitdb.getCollection("spit");

        Map<String,Object> map = new HashMap<>();

        map.put("content","我要吐槽");
        map.put("userid","9999");
        map.put("visits",123);
        map.put("publishtime",new Date());

        Document document = new Document(map);
        spit.insertOne(document); //出入数据
        client.close();
    }

    /**
     * 修改
     */
    @Test
    public void update(){
        //建立连接
        MongoClient client = new MongoClient("127.0.0.1");
        //获取数据库
        MongoDatabase spitdb = client.getDatabase("spitdb");
        //获取集合
        MongoCollection<Document> spit = spitdb.getCollection("spit");

        BasicDBObject bson = new BasicDBObject("userid","1013");
        BasicDBObject bson1 = new BasicDBObject("$set",new BasicDBObject("visits",1));
        spit.updateOne(bson,bson1);
        client.close();
    }
}
